package com.hanbang.taitaigou.ui.activity.home;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.model.SearchGoodsData;
import com.hanbang.taitaigou.ui.activity.application.MyApplication;
import com.hanbang.taitaigou.ui.activity.base.BaseActivity;
import com.hanbang.taitaigou.ui.activity.taitaigou.ProductDetailsActivity;
import com.hanbang.taitaigou.ui.widget.GridViewForScrollView;
import com.hanbang.taitaigou.ui.widget.ScaleImageView;
import com.hanbang.taitaigou.ui.widget.XTextView;
import com.hanbang.taitaigou.utils.db.GwcDbUtil;
import com.hanbang.taitaigou.utils.db.RecordSQLiteOpenHelper;
import com.hanbang.taitaigou.utils.http.BitmapUtil;
import com.hanbang.taitaigou.utils.http.HttpCallBack;
import com.hanbang.taitaigou.utils.http.HttpLocalUtils;
import com.hanbang.taitaigou.utils.http.HttpRequestParams;
import com.hanbang.taitaigou.utils.http.JsonHelper;
import com.hanbang.taitaigou.utils.ui.LogUtils;
import com.hanbang.taitaigou.utils.ui.ToastUtils;
import com.hanbang.taitaigou.utils.ui.UiUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Fangzh on 2016/3/30.
 */
public class SearchActivity extends BaseActivity {
    private ImageView back;
    private EditText search_et;
    private TextView search_tv;
    private ScrollView swipe_target;
    private GridViewForScrollView history_grid, goods_grid;
    //历史记录的集合
    private ArrayList<String> list = new ArrayList();
    private HistoryAdapter historyAdapter;


    /*搜索的货物展示*/
    private ArrayList<SearchGoodsData> goodsList = new ArrayList<>();
    /*搜索结果的Adapter*/
    private MyGoodsAdapter myadapter;

    //数据库
    private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
    private SQLiteDatabase db;

    //历史记录
    private LinearLayout ll_lsjl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_activity);
        initView();
        // 第一次进入查询所有的历史记录
        queryData("");
    }

    private void initView() {
        swipe_target = (ScrollView) findViewById(R.id.swipe_target);
        back = (ImageView) findViewById(R.id.back);
        search_et = (EditText) findViewById(R.id.search_et);
        search_tv = (TextView) findViewById(R.id.search_tv);
        history_grid = (GridViewForScrollView) findViewById(R.id.history_grid);
        goods_grid = (GridViewForScrollView) findViewById(R.id.goods_grid);
        ll_lsjl = (LinearLayout)findViewById(R.id.ll_lsjl);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        search_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!search_et.getText().toString().equals("")) {
                    list.clear();
                    String tempName = search_et.getText().toString();
                    insertData(tempName);
                    // 第一次进入查询所有的历史记录
                    queryData("");
                    getGoodsGrid(search_et.getText().toString());
                }
            }
        });
    }

    /*请求查询商品的方法*/
    private void getGoodsGrid(String keyWord) {
        HttpRequestParams httpRequestParams = new HttpRequestParams("SearchGoods");
        httpRequestParams.addBodyParameter("User_id", MyApplication.shangjiaId+"");
        httpRequestParams.addBodyParameter("keyword", keyWord);
        httpManager.post(httpRequestParams, new HttpCallBack<String>(this, "正在加载...") {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    goodsList.clear();
                    JSONObject json = new JSONObject(result);
                    JSONArray array = json.getJSONArray("result");
                    goodsList.addAll(JsonHelper.parseCollection(array, ArrayList.class, SearchGoodsData.class));
                    //如果搜索到商品就隐藏上面的历史搜索记录，没有就显示
                    if(goodsList.size()>0){
                        ll_lsjl.setVisibility(View.GONE);
                    }else{
                        ll_lsjl.setVisibility(View.VISIBLE);
                    }

                    //搜索结果GridView设置适配器
                    myadapter = new MyGoodsAdapter();
                    goods_grid.setAdapter(myadapter);
                    myadapter.notifyDataSetChanged();
                } catch (JSONException e) {

                }
            }
        });
    }

    /*查询数据库*/
    private void queryData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select * from records  order by id desc limit 0,12 ", null);
        while (cursor.moveToNext()) {
            String name = cursor.getString(1);
            LogUtils.i("ttt", "数据库获取的结果是：" + name);
            list.add(name);
            historyAdapter = new HistoryAdapter();
            history_grid.setAdapter(historyAdapter);
        }
    }

    /*往数据库插入数据*/
    private void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /*历史记录的Adapter*/
    class HistoryAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // 常见的优化ViewHolder
            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.history_item, null);
                viewHolder.history_item_tv = (TextView) convertView.findViewById(R.id.history_item_tv);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.history_item_tv.setText(list.get(position).toString());
            final String content=viewHolder.history_item_tv.getText().toString();
            viewHolder.history_item_tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getGoodsGrid(content);
                    search_et.setText(content);
                }
            });
            return convertView;
        }
    }

    class ViewHolder {
        TextView history_item_tv;
    }


    /*搜索结果adapter*/
    class MyGoodsAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return goodsList.size();
        }

        @Override
        public Object getItem(int position) {
            return goodsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // 常见的优化ViewHolder
            ViewHolder viewHolder;
            final SearchGoodsData itemData = (SearchGoodsData) getItem(position);
            final SearchGoodsData sgd = goodsList.get(position);
            if (null == convertView) {
                viewHolder = new ViewHolder();
                convertView = UiUtils.getInflaterView(SearchActivity.this, R.layout.home_list_griditem);
                viewHolder.grid_image = (ScaleImageView) convertView.findViewById(R.id.grid_image);
                viewHolder.tv_gname = (TextView) convertView.findViewById(R.id.tv_gname);
                viewHolder.tv_gunit = (TextView) convertView.findViewById(R.id.tv_gunit);
                viewHolder.sell_price = (TextView) convertView.findViewById(R.id.sell_price);
                viewHolder.tv_oriprice = (XTextView) convertView.findViewById(R.id.tv_oriprice);
                viewHolder.jiahao = (ImageView) convertView.findViewById(R.id.jiahao);
                viewHolder.grid_layout = (LinearLayout) convertView.findViewById(R.id.grid_layout);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            //获取数据
            imageManager.bind(viewHolder.grid_image, HttpLocalUtils.getHttpFileUrl(sgd.getImg_url()), BitmapUtil.getImageOptionsBuilder().build());
            viewHolder.tv_gname.setText(sgd.getGname());
            viewHolder.tv_gunit.setText(sgd.getPknum() + sgd.getUnit());
            viewHolder.sell_price.setText("￥" + sgd.getRetail_price());
            viewHolder.tv_oriprice.setText("￥" + sgd.getMarket_price());

            viewHolder.grid_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(SearchActivity.this, ProductDetailsActivity.class);
                    intent.putExtra("id", sgd.getId() + "");
                    intent.putExtra("title", search_et.getText().toString());
                    intent.putExtra("number", sgd.getNumber() + "");
                    startActivityForResult(intent, 999);
                    myadapter.notifyDataSetChanged();
                }
            });
            viewHolder.jiahao.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (GwcDbUtil.addGoodAutoNumber(itemData.getDbGwcData())) {
                        itemData.setNumber(itemData.getNumber() + 1);
                        myadapter.notifyDataSetChanged();
                        if (itemData.getNumber() != 0) {
                            ToastUtils.show(SearchActivity.this, "已添加到购物车", ToastUtils.LENGTH_SHORT);
                        } else {
                            ToastUtils.show(SearchActivity.this, "已添加到购物车", ToastUtils.LENGTH_SHORT);
                        }
                    }
                }
            });
            return convertView;
        }

        class ViewHolder {
            ScaleImageView grid_image = null;
            TextView tv_gname = null;
            TextView tv_gunit = null;
            TextView sell_price = null;
            XTextView tv_oriprice = null;
            LinearLayout grid_layout;
            ImageView jiahao;
        }
    }
}
